var islocked = false;
var keywords = new Array();
var cursor = -1;

var getName = function(){
    return $(".brandselector");
};

var getContainer = function(){
    return $(".brandviewer");
};

var getBrand = function(){
    if(islocked){
        return false;
    }
    var para = {};
    para.brand = keywords[cursor];

    var obj = {};
    obj.type = "GET";
    obj.data = para;
    obj.url = Globals.define.urlPrefix + "/json/getbrand";
    obj.timeout = 20000;
    obj.success = getBrand_cb.success;
    obj.error = getBrand_cb.error;
    
    islocked = true;
    $.ajax(obj);
};

var getBrand_cb = {
    success: function(json) {
        if (json !== "") {
            eval("var rt=" + json);
        } else {
            return true;
            //("提交成功，但是返回值为空");
        }

        var elist = "<ul>";
        if (null != rt.brandlist && rt.brandlist.length > 0) {
            for (var i = 0; i < rt.brandlist.length; i++) {
                var s = rt.brandlist[i];
                elist += '<li><a href="javascript:void(0)">';
                elist += s;
                elist += '</a></li>';
            }
        } else {
            elist += '<li>请输入公司名</li>';
        }
        elist += '</ul>';

        getContainer().eq(cursor).html(elist);
        getContainer().eq(cursor).show();

        islocked = false;
        return true;
    },
    error: function(xmlHttp, status, err) {
        islocked = false;
        return true;
    }
};

var bindEvent = function() {
    getName().each(function(m){
        keywords.push($.trim($(this).val()));

        $(this).keyup(function(e){
            if (e.which == 13){//回车
                return false;
            }

            cursor = m;
            if (keywords[cursor] == $.trim($(this).val())) {
                return false;
            }

            keywords[cursor] = $.trim($(this).val());

            if(keywords[cursor] == ""){
                getContainer().eq(cursor).html('<ul><li>请输入公司名</li></ul>');
                getContainer().eq(cursor).show();
                return false;
            }

            getBrand();
            return true;
        });
    });

    getContainer().each(function(m){
        $(this).click(function(e){
            var el = e.target;
            var node = $(el);
            if (!$.nodeName(el, "a")) {
                return false;
            }
            var name = node.text();
            getName().eq(m).val(name);
            $(this).hide();
        });
    });
};

(function() {
    bindEvent();
})();

